package server;


import server.interfaces.ITimer;
import server.interfaces.ITimerManager;

import com.CharNotValidException;
import com.Event;
import com.LedsManager;
import com.ParamsLabel;
import com.sun.spot.resources.transducers.LEDColor;
import com.sun.spot.util.Utils;

public class Timer implements ITimer {
	
	private String ID;
	private boolean periodic;
	private long timeout;
	private Event backEvent;
	private boolean terminated;
	private ITimerManager timerManager;
	
	public Timer(String timerID, ITimerManager timerManager, boolean periodic, long timeout, Event backEvent)
	{
		this.ID = timerID;
		this.timerManager = timerManager;
		this.periodic = periodic;
		this.timeout = timeout;
		this.backEvent = backEvent;
		try {
			backEvent.setParam(ParamsLabel.TMR_ID, this.ID);
		}
		catch (CharNotValidException e) {
			LedsManager.error(LEDColor.GREEN);
			e.printStackTrace();
		}
		this.terminated = false;
	}
	
	public void reset() {
		terminated = true;		
	}
	
	public void run() {
		do {
			Utils.sleep(this.timeout);
			if (!terminated )
				this.timerManager.getExecutionEngine().send(
						this.backEvent.getSourceID(),
						this.backEvent.getTargetID(),
						backEvent,
						true);
		}
		while(this.periodic && !this.terminated );
		
		this.timerManager.removeTimer(this.ID);
	}

	public String getID() {
		return ID;
	}
	
}
